package com.trailer.base.base

import android.app.ActivityManager
import android.app.Application
import android.os.Process
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadSir
import com.tencent.mmkv.MMKV
import com.trailer.base.BuildConfig
import com.trailer.base.config.IConfig
import com.trailer.base.config.IConfigInit
import com.trailer.base.emptyview.callback.*
import io.reactivex.plugins.RxJavaPlugins

abstract class BApp : Application(), IConfigInit {
    override fun onCreate() {
        super.onCreate()
        if (shouldInit()) {
            instance = this

            initUmeng()
            initMMKV()
            initRxJava()
            initLoadSir()
            init()
        }
    }

    protected abstract fun init()
    private fun initUmeng() {
        //            UMConfigure.init(this, "5bc6e22cb465f50d120001f9", "default", 0, null);
    }


    private fun initRxJava() {
        RxJavaPlugins.setErrorHandler {
            it.printStackTrace()
        }
    }



    private fun initMMKV() {
        val rootDir = MMKV.initialize(this)
        println("mmkv root: $rootDir")
    }

    private fun initLoadSir() {
        LoadSir.beginBuilder()
                .addCallback(ErrorCallback())
                .addCallback(EmptyCallback())
                .addCallback(LoadingCallback())
                .addCallback(TimeoutCallback())
                .addCallback(CustomCallback())
                .addCallback(ToLoginCallback())
                .addCallback(AnimateCallback())
                .setDefaultCallback(SuccessCallback::class.java)
                .commit()
    }

    private fun shouldInit(): Boolean {
        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val processInfos = am.runningAppProcesses
        val mainProcessName = packageName
        val myPid = Process.myPid()
        for (info in processInfos) {
            if (info.pid == myPid && mainProcessName == info.processName) {
                return true
            }
        }
        return false
    }

    companion object {
        const val TAG = "MiPush"
        private var instance: BApp? = null


        @JvmStatic
        fun instance(): BApp? {
            return instance
        }
    }
}
